"""
数据库连接模块
"""
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, scoped_session

from lemon_backend.config.settings import Config

# 创建数据库引擎
engine = create_engine(Config.DATABASE_URI)

# 创建会话工厂
session_factory = sessionmaker(autocommit=False, autoflush=False, bind=engine)

# 创建线程安全的会话
db_session = scoped_session(session_factory)

# 创建基础模型类
Base = declarative_base()
Base.query = db_session.query_property()

def init_db():
    """初始化数据库，创建所有表"""
    # 导入所有模型以确保它们被注册到Base中
    import lemon_backend.models.user  # noqa
    
    # 创建所有表
    Base.metadata.create_all(bind=engine)

def shutdown_db():
    """关闭数据库连接"""
    db_session.remove()
